<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title-box"></div>
      <!-- ref获取控件，model是表单数据，rule表单规则 -->
      <el-form ref="loginForm" :model="loginForm" :rules="rules">
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            type="password"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-button type="primary" class="login-btn" @click="loginFn"
          >登陆</el-button
        >
        <el-link href="" target="info" ><router-link to="/reg">去注册</router-link></el-link>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api/index.js'
import { mapMutations } from 'vuex'
export default {
  name: 'my-login',
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/, message: '输入的密码必须以字母开头', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['updateToken']),
    loginFn () {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          // console.log(this.loginFn)
          const { data: res } = await loginAPI(this.loginForm)
          console.log(res)
          if (res.code !== 0) {
            return this.$message.error(res.message)
          } else {
            this.$message.success(res.message)
            this.updateToken(res.token)
            this.$router.push('/')
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: url("@/assets/images/login_bg.jpg") center;
  background-size: cover;
  height: 100%;

  .login-box {
    width: 400px;
    height: 335px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0 30px;
    box-sizing: border-box;

    .title-box {
      height: 60px;
      background: url("@/assets/images/login_title.png")
        center no-repeat;
    }

    .login-btn {
      width: 100%;
    }
  }
}
</style>
